package com.zz.yt.lib.ui.base;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.style.ClickableSpan;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.ColorInt;
import androidx.annotation.IdRes;
import androidx.annotation.NonNull;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.ResourceUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.whf.android.jar.app.Latte;
import com.whf.android.jar.net.HttpCode;
import com.whf.android.jar.net.callback.ISuccess;
import com.whf.android.jar.net.gson.HttpGsonUtils;
import com.whf.android.jar.popup.listener.OnClickDecisionListener;
import com.whf.android.jar.util.log.LatteLogger;
import com.zz.yt.lib.annex.QbSdkUtils;
import com.zz.yt.lib.annex.constant.PictureConstant;
import com.zz.yt.lib.annex.document.DocumentView;
import com.zz.yt.lib.annex.document.bean.AnnexBean;
import com.zz.yt.lib.annex.document.util.AnnexUtil;
import com.zz.yt.lib.annex.listener.OnClickAnnexLoading;
import com.zz.yt.lib.annex.listener.OnClickPictureCallback;
import com.zz.yt.lib.annex.picture.PictureView;
import com.zz.yt.lib.annex.picture.bean.FilePathBean;
import com.zz.yt.lib.annex.popup.PicturePopup;
import com.zz.yt.lib.ui.R;
import com.zz.yt.lib.ui.callback.OnSelectDateStrCallback;
import com.zz.yt.lib.ui.listener.OnClickObjectListener;
import com.zz.yt.lib.ui.listener.OnClickStringListener;
import com.zz.yt.lib.ui.popup.view.CalendarEasyPopup;
import com.zz.yt.lib.ui.popup.view.CitySelectPopup;
import com.zz.yt.lib.ui.popup.view.TipsMinPopup;
import com.zz.yt.lib.ui.recycler.data.OrderFormEntity;
import com.zz.yt.lib.ui.recycler.holder.OtherClickableSpan;
import com.zz.yt.lib.ui.utils.AddressUtils;
import com.zz.yt.lib.ui.utils.DateKeysUtils;
import com.zz.yt.lib.ui.utils.DatesUtils;
import com.zz.yt.lib.ui.utils.ObjUtils;
import com.zz.yt.lib.ui.utils.SpannableStringUtils;
import com.zz.yt.lib.ui.view.mothOrYearSelect.MothOrYearSelectBuilder;
import com.zz.yt.lib.ui.view.mothOrYearSelect.OnMothOrYearSelectListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import me.yokeyword.fragmentation.anim.DefaultHorizontalAnimator;
import me.yokeyword.fragmentation.anim.FragmentAnimator;

/***
 * 界面
 * @author qf
 * @version 1.0
 * @version 2020-03-23
 */
public abstract class LatteDelegate extends PerCheckerDelegate implements IResponse,
        OnClickAnnexLoading, OnClickPictureCallback {

    private static final String TAG_OFFSET = "TAG_OFFSET";
    private static final int KEY_OFFSET = -123;

    /**
     * 保存处理数据(文件id)
     */
    protected final ArrayList<String> mFileIdArray = new ArrayList<>();

    /**
     * 判断上一个界面是否传过来bundle
     */
    protected boolean hasData;

    /**
     * 处理上一个页面传来的数据
     */
    protected void getData(Bundle bundle) {

    }

    /**
     * 编辑时赋值
     */
    protected void setEntry() {
    }

    /**
     * 获取值
     */
    protected boolean getEntry() {
        return true;
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        final Bundle mBundle = getArguments();
        if (mBundle != null) {
            hasData = true;
            getData(mBundle);
        }
    }

    @Override
    public FragmentAnimator onCreateFragmentAnimator() {
        return new DefaultHorizontalAnimator();
    }

    /**
     * Add the top margin size equals status bar's height for view.
     *
     * @param view The view.(只能使用，不建议重构)
     */
    protected final void addMarginTopEqualStatusBarHeight(@NonNull View view) {
        view.setTag(TAG_OFFSET);
        Object haveSetOffset = view.getTag(KEY_OFFSET);
        if (haveSetOffset != null && (Boolean) haveSetOffset) {
            return;
        }
        ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
        layoutParams.setMargins(layoutParams.leftMargin,
                layoutParams.topMargin + getStatusBarHeight(),
                layoutParams.rightMargin,
                layoutParams.bottomMargin);
        view.setTag(KEY_OFFSET, true);
    }

    /**
     * @return 是否是全屏
     */
    protected boolean isTopView() {
        return true;
    }

    private int getStatusBarHeight() {
        int resourceId = Latte.getBarHeight();
        return resourceId == -1 ? 36 : resourceId;
    }

    //******************************************************************************//

    /*** 是否是图片回调 */
    protected boolean isPd = false;
    protected PictureView mPictureView = null;
    protected DocumentView mDocumentView = null;

    @Override
    public void inFile(@NonNull final String fileUrl) {
        if (ObjectUtils.isNotEmpty(fileUrl)) {
            //是否是视频
            if (QbSdkUtils.inFlue(fileUrl)) {
                LatteLogger.i("查看图片视频(直接在线查看)");
                return;
            }
            startFileWithCheck(new OnClickObjectListener() {
                @Override
                public void onClick(Object index) {
                    final String name = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
                    download(fileUrl, name, new ISuccess() {
                        @Override
                        public void onSuccess(String response) {
                            hideLoading();
                            if (inFilePdfJs(name, response)) {
                                LatteLogger.i("通过pdf.sj查看");
                                return;
                            }
                            QbSdkUtils.openFileReader(context, response, null, null);
                        }
                    });
                }
            });
        }
    }

    protected boolean inFilePdfJs(final String fileName, final String fileUrl) {
        if (ObjectUtils.isNotEmpty(fileUrl) && QbSdkUtils.isPdfJs(fileUrl)) {
            startWebUi(fileName, "file:///android_asset/pdf/show_pdf.html?" + fileUrl);
            return true;
        }
        return false;
    }

    /**
     * @param documentView:附件
     */
    protected void initDocument(DocumentView documentView) {
        if (documentView != null) {
            documentView.setContext(this);
            documentView.setOnClickAnnexLoading(this);
            documentView.setRootView(PictureConstant.ALL);
            documentView.setClickPictureCallback(this);
            documentView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mDocumentView = (DocumentView) v;
                    isPd = false;
                }
            });
        }
    }

    /**
     * @param pictureView:图片附件
     */
    protected void initPicture(PictureView pictureView) {
        initPicture(pictureView, mRootView);
    }

    /**
     * @param pictureView:图片附件
     */
    protected void initPicture(PictureView pictureView, View rootView) {
        if (pictureView != null) {
            pictureView.setDisplay(true);
            pictureView.setClickPictureCallback(this);
            pictureView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    isPd = true;
                    mPictureView = (PictureView) v;
                }
            });
        }
    }

    /**
     * @param data:上传附件的回调。
     */
    @Override
    public void onSuccessPath(String data) {
        hideLoading();
        if (!TextUtils.isEmpty(data) && data.length() > 1) {
            if ("[".equals(data.substring(0, 1))) {
                final List<FilePathBean> filePathArray = HttpGsonUtils.fromJsonList(data, FilePathBean.class);
                if (filePathArray != null && !filePathArray.isEmpty()) {
                    for (FilePathBean filePath : filePathArray) {
                        setFilePath(filePath);
                    }
                }
            } else {
                final FilePathBean filePath = HttpGsonUtils.fromJson(data, FilePathBean.class);
                setFilePath(filePath);
            }
        }
    }

    /**
     * @param filePath:上传附件的回调解析的对象。
     */
    protected void setFilePath(FilePathBean filePath) {
        if (filePath != null) {
            //保存上传文件的id
            mFileIdArray.add(getIdFile(filePath));
        }
    }

    @Override
    public void onCallback(List<String> selectList) {

    }

    @Override
    public void remove(int position) {
        if (mFileIdArray.size() > position) {
            mFileIdArray.remove(position);
        }
    }

    @Override
    public boolean isFile() {
        if (mFileIdArray.size() == 0) {
            ToastUtils.showShort("请选择文件上传");
            return true;
        }
        return false;
    }

    /**
     * @param filePathBean:取出上传附件的id
     */
    protected String getIdFile(FilePathBean filePathBean) {
        if (filePathBean == null) {
            return null;
        }
        dataDocument(filePathBean);
        return filePathBean.getId();
    }

    protected void dataDocument(FilePathBean filePathBean) {
        if (isPd && mPictureView != null && filePathBean != null) {
            //图片的返回
            mPictureView.addData(filePathBean.getPath());
        }
        if (!isPd && mDocumentView != null && filePathBean != null) {
            //图片的返回
            mDocumentView.addData(new AnnexBean(filePathBean.getId(), filePathBean.getFileName(), filePathBean.getPath()));
        }
    }

    @Override
    public String getFile() {
        return ObjUtils.getFieldArrayId(mFileIdArray);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        AnnexUtil.Bundle().onResultAnnex(requestCode, resultCode, data, new AnnexUtil.OnClickListener() {
            @Override
            public void onClick(List<String> path) {
                onCallback(path);
                if (mDocumentView != null) {
                    mDocumentView.setMaxCount(9 - path.size());
                }
            }
        });
    }

    //************************************ 提交提示 ***********************************************//

    /***
     * 提交数据
     */
    protected void save(OnClickDecisionListener listener) {
        save("是否确认提交", listener);
    }

    /***
     * 提交数据
     */
    protected void save(String title, OnClickDecisionListener listener) {
        KeyboardUtils.hideSoftInput(mRootView);
        TipsMinPopup.create()
                .setTitle(title)
                .setOnClickListener(listener)
                .popup();
    }

    /***
     * 提交数据
     */
    protected void save(PicturePopup.OnClickListener listener) {
        KeyboardUtils.hideSoftInput(mRootView);
        PicturePopup.create(Latte.getActivity())
                .setPhotograph("提交")
                .setLocal("保存")
                .setClickListener(listener)
                .popup();
    }


    /**
     * @param response:默认返回处理
     * @param listener：返回的data
     */
    @Deprecated
    protected void code(String response, OnClickStringListener listener) {
        hideLoading();
        if (ObjectUtils.isEmpty(response) || listener == null) {
            return;
        }
        LatteLogger.json(response);
        final int code = ObjUtils.getCode(response);
        if (HttpCode.CODE_200 == code) {
            final String data = ObjUtils.getData(response);
            listener.onClick(data);
        } else {
            onError(code, Latte.getMessage(response));
        }
    }

    //************************************ setOrderForm *******************************************//

    /**
     * @param viewId：控件-设置键值对
     * @param orderEntity：值-设置键值对
     */
    protected final void setOrderForm(@IdRes int viewId, @NonNull OrderFormEntity orderEntity) {
        setText(viewId, SpannableStringUtils.getBuilder(orderEntity.getText())
                .append(orderEntity.getValue() == null ? "" : orderEntity.getValue())
                .setClickSpan(orderEntity.isValueColor() ? accentSpan : otherSpan)
                .create());
    }

    /**
     * @param viewId：控件-设置键值对
     * @param orderEntity：值-设置键值对
     */
    protected final void setOrderForm(@IdRes int viewId, @NonNull OrderFormEntity orderEntity, @ColorInt int color) {
        setText(viewId, SpannableStringUtils.getBuilder(orderEntity.getText())
                .append(orderEntity.getValue() == null ? "" : orderEntity.getValue())
                .setClickSpan(new OtherClickableSpan(color))
                .create());
    }


    /**
     * 键值对
     */
    protected final ClickableSpan otherSpan = OtherClickableSpan.create(R.color.textColor_85);

    protected final ClickableSpan accentSpan = OtherClickableSpan.create(R.color.colorAccent);


    //************************************* 获取布局控件  *****************************************/

    /**
     * 获取布局控件
     */
    protected ViewGroup rootView() {
        return Latte.getActivity()
                .getWindow()
                .getDecorView()
                .findViewById(android.R.id.content);
    }

    /************************************* 设置获取值  *****************************************/

    protected boolean isHintEmpty(int viewId) {
        TextView depText = getTextView(viewId);
        if (depText != null && getTagStr(viewId).isEmpty()) {
            ToastUtils.showShort(getHintStr(viewId));
            return true;
        }
        return false;
    }

    /**
     * 判断数据是否为空
     *
     * @param viewId：
     */
    protected boolean isEmpty(int viewId) {
        return isTextEmpty(viewId, getHintStr(viewId));
    }

    /**
     * 判断数据是否为空
     *
     * @param viewId：
     * @param text：
     */
    protected boolean isEmpty(int viewId, final CharSequence text) {
        return isTextEmpty(viewId, text);
    }

    /***
     * 判断数据是否为空
     * @param viewId：
     */
    protected boolean isTextEmpty(int viewId) {
        return isTextEmpty(viewId, getHintStr(viewId));
    }

    /**
     * 判断数据是否为空
     *
     * @param viewId：
     * @param text：
     */
    protected boolean isTextEmpty(int viewId, final CharSequence text) {
        TextView depText = getTextView(viewId);
        if (depText != null && depText.getText().toString().trim().isEmpty()) {
            ToastUtils.showShort(text);
            return true;
        }
        return false;
    }

    //****************************** 左、右两边图标点击事件  *********************************/

    protected void setOnTouchListenerLeft(int vieId, final View.OnClickListener listener) {
        //TextView左边图标点击事件
        setOnTouchListener(vieId, 0, listener);
    }

    /**
     * @param vieId:TextView右边图标点击事件
     * @param listener:点击事件处理
     */
    protected void setOnTouchListenerRight(int vieId, final View.OnClickListener listener) {
        setOnTouchListener(vieId, 2, listener);
    }

    /**
     * @param vieId:TextView四边图标点击事件
     * @param listener:点击事件处理
     */
    @SuppressLint("ClickableViewAccessibility")
    protected void setOnTouchListener(int vieId, final int i, final View.OnClickListener listener) {
        final TextView view = getTextView(vieId);
        if (view != null) {
            final int width = view.getWidth() - view.getPaddingRight();
            view.setOnTouchListener(new View.OnTouchListener() {
                @SuppressLint("ClickableViewAccessibility")
                public boolean onTouch(View v, MotionEvent event) {
                    // 得到一个长度为4的数组，分别表示左上右下四张图片(0.1.2.3)
                    Drawable drawable = getViewDrawables(view, i);
                    //如果右边没有图片，不再处理
                    if (drawable == null)
                        return false;
                    //如果不是按下事件，不再处理
                    if (event.getAction() != MotionEvent.ACTION_UP)
                        return false;
                    if (event.getX() > width - drawable.getIntrinsicWidth()) {
                        if (listener != null) {
                            listener.onClick(view);
                        }
                    }
                    return false;
                }
            });
        }
    }

    //****************************** 设置左边图标  *********************************/


    /**
     * @param image:左边按钮图片
     */
    protected void setLeftImage(int vieId, int image) {
        try {
            setLeftImage(vieId, ResourceUtils.getDrawable(image));
        } catch (Exception e) {
            LatteLogger.e(e.getMessage());
        }
    }

    /**
     * @param image:左边按钮图片
     */
    protected void setLeftImage(TextView textView, int image) {
        try {
            setLeftImage(textView, ResourceUtils.getDrawable(image));
        } catch (Exception e) {
            LatteLogger.e(e.getMessage());
        }
    }

    /**
     * @param image:左边按钮图片
     */
    protected void setLeftImage(int vieId, Drawable image) {
        setLeftImage(getTextView(vieId), image);
    }

    /**
     * @param image:左边按钮图片
     */
    protected void setLeftImage(TextView textView, Drawable image) {
        if (textView != null) {
            try {
                textView.setCompoundDrawablesWithIntrinsicBounds(image,
                        getViewDrawables(textView, 1),
                        getViewDrawables(textView, 2),
                        getViewDrawables(textView, 3));
            } catch (Exception e) {
                LatteLogger.e(e.getMessage());
            }
        }
    }

    //****************************** 设置右边图标  *********************************/

    /**
     * @param image:右边按钮图片
     */
    protected void setRightImage(int vieId, int image) {
        try {
            setRightImage(vieId, ResourceUtils.getDrawable(image));
        } catch (Exception e) {
            LatteLogger.e(e.getMessage());
        }
    }

    /**
     * @param image:右边按钮图片
     */
    protected void setRightImage(int vieId, Drawable image) {
        try {
            setRightImage(getTextView(vieId), image);
        } catch (Exception e) {
            LatteLogger.e(e.getMessage());
        }
    }

    /**
     * @param image:右边按钮图片
     */
    protected void setRightImage(TextView textView, int image) {
        try {
            setRightImage(textView, ResourceUtils.getDrawable(image));
        } catch (Exception e) {
            LatteLogger.e(e.getMessage());
        }
    }

    /**
     * @param image:右边按钮图片
     */
    protected void setRightImage(TextView textView, Drawable image) {
        if (textView != null) {
            try {
                textView.setCompoundDrawablesWithIntrinsicBounds(
                        getViewDrawables(textView, 0),
                        getViewDrawables(textView, 1),
                        image,
                        getViewDrawables(textView, 3));
            } catch (Exception e) {
                LatteLogger.e(e.getMessage());
            }
        }
    }


    /**
     * @param view:得到一个长度为4的数组，分别表示左上右下四张图片(0.1.2.3)
     * @param i:左上右下四张图片(0.1.2.3)
     */
    protected Drawable getViewDrawables(TextView view, int i) {
        if (view != null) {
            return view.getCompoundDrawables()[i];
        }
        return null;
    }

    //************************************ 常用监听 ***********************************************//

    protected void setOnTouchListener(@IdRes int viewId, View.OnTouchListener listener) {
        View view = getView(viewId);
        if (view != null) {
            view.setOnTouchListener(listener);
        }
    }

    protected void setOnLongClickListener(@IdRes int viewId, View.OnLongClickListener listener) {
        View view = getView(viewId);
        if (view != null) {
            view.setOnLongClickListener(listener);
        }
    }

    /*** 选择时间(默认日期<年月日>) */
    protected void onClickTime(OnClickStringListener listener) {
        onClickTime(DateKeysUtils.DATE, listener);
    }

    /*** 选择时间 */
    protected void onClickTime(@DateKeysUtils.Type int patternType, OnClickStringListener listener) {
        DatesUtils.create()
                .setType(patternType)
                .setOnClickStringListener(listener)
                .onClick();
    }

    /*** 选择时间 */
    protected void onClickTimeSingle(OnSelectDateStrCallback callback) {
        onClickTimeSingle(false, callback);
    }

    /**
     * @param callback:选择时间
     * @param toDay:true(只能选择今天及以后的时间)
     */
    protected void onClickTimeSingle(boolean toDay, OnSelectDateStrCallback callback) {
        CalendarEasyPopup
                .create(true, toDay)
                .setOnClickListener(callback)
                .popup();
    }

    /*** 选择时间段 */
    protected void onClickTimeMultiple(OnSelectDateStrCallback callback) {
        onClickTimeMultiple(false, callback);
    }

    /**
     * @param callback:选择时间段
     * @param toDay:true(只能选择今天及以后的时间)
     */
    protected void onClickTimeMultiple(boolean toDay, OnSelectDateStrCallback callback) {
        CalendarEasyPopup
                .create(false, toDay)
                .setOnClickListener(callback)
                .popup();
    }

    /**
     * @param listener:城市选择及回调
     */
    protected final void onClickCity(OnClickStringListener listener) {
        CitySelectPopup.create()
                .setOnClickListener(listener)
                .popup();
    }

    /**
     * @param listener:省市区选择及回调
     */
    protected final void onClickAreas(OnClickStringListener listener) {
        AddressUtils.getInstance()
                .onClickListener(listener)
                .popup();
    }


    /*** 选择日期段
     * @param isMonth:true选择年月，false选择年
     * */
    protected void onClickDate(final boolean isMonth, final OnSelectDateStrCallback callback) {
        Calendar selectedDate = Calendar.getInstance();

        Calendar startDate = Calendar.getInstance();
        startDate.set(2000, 0, 1);

        Calendar endDate = Calendar.getInstance();
        endDate.set(selectedDate.getWeekYear() + 5, 11, 1);

        new MothOrYearSelectBuilder(getContext(),
                new OnMothOrYearSelectListener() {
                    @Override
                    public void onMothOrYearSelect(Date date, Date date2) {
                        SimpleDateFormat pattern = TimeUtils.getSafeDateFormat("yyyy");
                        if (isMonth) {
                            pattern = TimeUtils.getSafeDateFormat("yyyy-MM");
                        }
                        String startTime = TimeUtils.date2String(date, pattern);
                        String endTime = TimeUtils.date2String(date2, pattern);
                        if (callback != null) {
                            callback.selectDate(startTime, endTime);
                        }
                    }
                })
                .setMothOrYear(isMonth)
                .setDividerColor(Color.DKGRAY)
                .setContentTextSize(16)
                .setDecorView(rootView())
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setOutSideColor(0x00000000)
                .setOutSideCancelable(true)
                .build()
                .show();
    }

}
